package com.tonghe.handler.security;

import com.alibaba.fastjson.JSON;
import com.tonghe.domain.ResponseResult;
import com.tonghe.enums.AppHttpCodeEnum;
import com.tonghe.utils.WebUtils;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Date:2022/2/22- 02- 22- 15:56
 * 认证 异常 Handler
 **/
@Component // 需注入spring容器中
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {


    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authenticationException) throws IOException, ServletException {

        authenticationException.printStackTrace();

        ResponseResult result = null;

        // 通过异常捕获得到 BadCredentialsException 为用户名或者密码错误异常
        if(authenticationException instanceof BadCredentialsException){
            result = ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_ERROR.getCode(),authenticationException.getMessage());

            //通过异常捕获得到 InsufficientAuthenticationException 为权限不足或者需要登陆异常
        }else if(authenticationException instanceof InsufficientAuthenticationException){
            result = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }else {
            // 其他异常
            result = ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR.getCode(),"认证或授权失败");
        }
        WebUtils.renderString(response, JSON.toJSONString(result));//响应给前端

    }
}
